import { Injectable } from '@nestjs/common';
import { UserService } from 'src/user/user.service';
import * as bcrypt from 'bcrypt';
import { UserEntity } from 'src/user/entities/user.entity';
import { JwtService } from '@nestjs/jwt';
import { RecordLoginService } from 'src/record_login/record_login.service';

@Injectable()
export class AuthService {
  constructor(
    private readonly userService: UserService,
    private jwtService: JwtService,
    private readonly recordLoginService: RecordLoginService,
  ) {}
  // 登录前校验
  async validateUser(username: string, password: string) {
    const user = await this.userService.findOneByUsername(username);
    // console.log('-----login-----', user);
    if (user && bcrypt.compareSync(password, user.password)) {
      return { username: user.username, id: user.id };
    }
    return null;
  }

  async login(user: UserEntity, ip: string) {
    // 创建登录日志
    await this.recordLoginService.create({
      user_id: user.id,
      ip,
    });

    return this.jwtService.sign({
      username: user.username,
      sub: user.id,
    });
  }
}
